package com.xzd.common;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.xzd.util.ExcelUtils;
import com.xzd.util.ReflectUtils;

@SuppressWarnings("serial")
public class BaseAction extends ActionSupport {
	protected HttpServletResponse response = null;
	protected HttpServletRequest request = null;
	protected Map<String, Object> session = null;
	
	protected int start;
	protected int limit;
	
	
	protected HttpServletResponse getResponse() {
		response = ServletActionContext.getResponse();
		response.setContentType("text/html;charset=UTF-8");
		return response;
	}
		
	protected HttpServletRequest getRequest() {
		request = ServletActionContext.getRequest();
		return request;
	}
	
	protected Map<String, Object> getSession() {
		session = ActionContext.getContext().getSession();
		return session;
	}
	
	protected void responsePrint(String str) throws IOException{
		//System.out.println(str);
		getResponse().getWriter().print(str);
	}
	
	/**
	 * 导出当前表到Excel
	 * @param list
	 */
	public void exportCurentTableToExcel(List<? extends Object> list,String exportData,String exportFileName) {
		
		JSONArray jsonarray = JSONArray.fromObject(exportData);
		
		Object[] title = null;
		List<Object[]> data = new ArrayList<Object[]>();
			
		ExcelUtils utils = new ExcelUtils();
		if(jsonarray.size() > 0){
			title = ((JSONArray)jsonarray.get(0)).toArray();		//列头的中文名称对应ext页面中的ColumnHeader
		}
		
		Object[] fieldArray = ((JSONArray)jsonarray.get(1)).toArray();	//对应页面中的DataIndex
		
		Object obj;
		for(int i=0 ;i<list.size(); i++) {
			obj = list.get(i);
			
			if(obj instanceof Object[]) {
				data.add((Object[])obj);
			} else {
				Object[] objArray = new Object[fieldArray.length];
				for(int j=0; j<objArray.length; j++) {
					try {
						objArray[j] = ReflectUtils.getGetMethod(fieldArray[j].toString(), obj).invoke(obj);
					} catch (Exception e) {
						objArray[j] = "";
					}
				}
				data.add(objArray);
			}

		}
		
		utils.addTable(exportFileName,title, data);		
		utils.autoColumn();				
		utils.export(getRequest(), getResponse(), exportFileName + ".xls");
	}
	
	protected boolean isValidity(Object obj){
		
		if(obj != null){
			if(obj instanceof String){
				if(!obj.equals("")){
					return true;
				}
			}
			return true;
		}
		return false;
	}
	
	public int getStart() {
		return start;
	}
	public void setStart(int start) {
		this.start = start;
	}
	public int getLimit() {
		return limit;
	}
	public void setLimit(int limit) {
		this.limit = limit;
	}



}
